<template>
  <div class="warp">
    <div class="btnBox">
      <div class="inputBox">
        <span>宽:</span>
        <a-input-number
          v-model:value="wValue"
          placeholder="请输入"
          :min="1"
          style="width: 80px; margin: 0px 0px 0px 10px"
        />
        <span>&nbsp;px&nbsp;</span>
        <span>&nbsp;&nbsp;&nbsp;高:</span>
        <a-input-number
          v-model:value="hValue"
          placeholder="请输入"
          :min="1"
          style="width: 80px; margin: 0px 0px 0px 10px"
        />
        <span>&nbsp;px&nbsp;</span>
      </div>
      <div>
        <a-button
          type="primary"
          @click="submit"
          :loading="butloading"
          style="margin: 0px 20px 0px 30px"
          >开始处理</a-button
        >
        <a-button type="primary" @click="reset">重置</a-button>
      </div>
    </div>
    <div>
      <el-input
        v-model="textarea"
        :rows="5"
        type="textarea"
        placeholder="请输入网址,用回车换行哦"
        class="textarea"
      />
    </div>
  </div>
  <div class="download">
    <span class="flexSpan">
      全部数据：{{ storeArray.length }}&nbsp;&nbsp;&nbsp;&nbsp;正确数量：{{
        correctLenght
      }}&nbsp;&nbsp;&nbsp;&nbsp;错误数量：{{ errorLength }}
    </span>
    <a-button type="primary" @click="download"
      ><DownloadOutlined />下载</a-button
    >
  </div>
  <a-table
    :row-selection="rowSelection"
    :columns="columns"
    :data-source="tableData"
    size="middle"
    :scroll="{ y: 400 }"
    :loading="tabloading"
  >
    <template #status="{ text }">
      <div style="color: cadetblue" v-if="text == '成功'">成功</div>
      <div style="color: red" v-else>失败</div>
    </template>
  </a-table>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed, unref } from "vue";
import axios from "axios";
import { message } from "ant-design-vue";
import { phraselist } from "../until/phrase";
import { DownloadOutlined } from "@ant-design/icons-vue";
export default defineComponent({
  components: {
    DownloadOutlined,
  },
  setup() {
    let tableData: any = ref([]);
    let tableHead: any = ref([]);
    let butloading = ref<boolean>(false);
    let tabloading = ref<boolean>(false);
    let phrase: any = ref([]);
    let storeArray: any = ref([]);
    let newArray: any = ref([]);
    let datalist: any = [];
    let tabIndex = 0;
    let correctLenght: any = ref(0);
    let errorLength: any = ref(0);
    const selectedRowKeys: any = ref([]);
    const selectList: any = ref([]);
    const wValue = ref<string>("");
    const hValue = ref<string>("");
    const textarea = ref("");
    const columns = [
      {
        title: "图片地址",
        dataIndex: "url",
        ellipsis: true,
      },
      {
        title: "状态",
        dataIndex: "status",
        slots: { customRender: "status" },
      },
    ];
    onMounted(() => {
      refresh();
    });
    const refresh = () => {
      let number = random(0, phraselist.length);
      phrase.value = [];
      phraselist[number].forEach((e) => {
        phrase.value.push(e);
      });
    };
    const random = (min: any, max: any) => {
      return Math.floor(Math.random() * (max - min)) + min;
    };
    const reset = () => {
      textarea.value = "";
      correctLenght.value = 0;
      errorLength.value = 0;
      tableData.value = [];
      storeArray.value = [];
    };
    const submit = async () => {
      if (wValue.value == "") {
        message.error("请输入图片的宽度");
        return;
      }
      if (hValue.value == "") {
        message.error("请输入图片的高度");
        return;
      }
      if (textarea.value == "") {
        message.error("请输入网址");
        return;
      }
      if (textarea.value.charAt(textarea.value.length - 1) == "\n") {
        textarea.value = textarea.value.substring(0, textarea.value.length - 1);
      }
      console.log(textarea.value);
      datalist = textarea.value.split("\n");
      tableData.value = [];
      storeArray.value = [];
      correctLenght.value = 0;
      errorLength.value = 0;
      butloading.value = true;
      tabloading.value = true;
      console.log(datalist);
      for (const fn of datalist) {
        if (fn) {
          let obj = {
            url: fn,
            x: 0,
            y: 0,
            w: wValue.value,
            h: hValue.value,
          };
          await analysis(obj);
        }
      }
      tabloading.value = false;
      tableData.value = storeArray.value;
    };
    const analysis = async (e: any) => {
      let p1 = await getH1(e);
      await Promise.all([p1])
        .then((result: any) => {
          let status = "";
          let name = e.url;
          if (result[0].status == "200") {
            name = result[0].headers["content-disposition"]
              .split(";")[1]
              .split("=")[1];
            correctLenght.value++;
            status = "成功";
          } else {
            errorLength.value++;
            status = "失败";
          }
          storeArray.value.push({
            key: tabIndex++,
            url: name,
            status: status,
            data: result[0].data,
          });
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const getH1 = (data: any) => {
      return new Promise((resolve, reject) => {
        axios({
          method: "get",
          url:
            "/api/imageInfo?url=" +
            data.url +
            "&x=" +
            data.x +
            "&y=" +
            data.y +
            "&w=" +
            data.w +
            "&h=" +
            data.h,
          responseType: "blob",
        })
          .then((res) => {
            resolve(res);
            butloading.value = false;
          })
          .catch((err) => {
            message.error("服务器连接失败");
            butloading.value = false;
            reject(err);
          });
      });
    };
    const download = async () => {
      if (selectList.value.length == 0) {
        message.error("请选择下载内容");
        return;
      }
      console.log(selectList.value);
      for (const fn of selectList.value) {
        if (fn.status == "成功") {
          await downloadFile(fn.url, fn.data);
        }
      }
    };
    const downloadFile = (fileName: any, content: any) => {
      let link = document.createElement("a");
      link.href = URL.createObjectURL(content);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(link.href);
    };
    const onSelectChange = (key: any, list: any) => {
      selectedRowKeys.value = key;
      selectList.value = list;
    };
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: unref(selectedRowKeys),
        onChange: onSelectChange,
        hideDefaultSelections: true,
        selections: [
          {
            key: "all-data",
            text: "选择全部",
            onSelect: () => {
              selectedRowKeys.value = [...tableData.value.keys()];
            },
          },
        ],
      };
    });
    return {
      tableHead,
      tableData,
      phrase,
      butloading,
      storeArray,
      textarea,
      wValue,
      hValue,
      newArray,
      selectList,
      correctLenght,
      errorLength,
      columns,
      tabloading,
      selectedRowKeys,
      rowSelection,
      refresh,
      onSelectChange,
      download,
      reset,
      submit,
    };
  },
});
</script>
<style>
body {
  background: url("../assets/background.svg");
}
</style>

<style lang="less" scoped>
.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
/deep/ .el-table .warning-row {
  color: red;
}
/deep/ .el-table .success-row {
  color: #606266;
}
.flexSpan {
  display: flex;
  align-items: center;
}
.phrase {
  position: absolute;
  left: 50px;
  top: 0px;
  padding-top: 80px;
  font-family: cursive;
  writing-mode: vertical-lr;
  font-size: 40px;
  opacity: 0.5;
  cursor: pointer;
}

.phrtext {
  margin-top: 50px;
}
.flexbox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.el-table--border {
  background-color: rgba(0, 0, 0, 0);
}
.download {
  display: flex;
  justify-content: space-between;
  margin: 10px 0px;
}
/deep/ .el-table tr {
  background-color: rgba(0, 0, 0, 0);
}
.warp {
  margin: 0 auto;
  position: relative;
  z-index: 9;
}

.btnBox {
  display: flex;
  margin-bottom: 20px;
}
.textarea {
  /deep/ textarea {
    max-height: 400px;
  }
}
.inputBox {
  display: flex;
  span {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
</style>
